<!DOCTYPE html>
<html lang="en"><head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1"><!-- Begin Jekyll SEO tag v2.8.0 -->
<title>0106: D Snippets II - A Generic Observer | gtkDcoding</title>
<meta name="generator" content="Jekyll v4.3.4" />
<meta property="og:title" content="0106: D Snippets II - A Generic Observer" />
<meta name="author" content="Ron Tarrant" />
<meta property="og:locale" content="en_US" />
<meta name="description" content="This GTK Tutorial covers a generic Observer pattern implemented in D." />
<meta property="og:description" content="This GTK Tutorial covers a generic Observer pattern implemented in D." />
<link rel="canonical" href="http://localhost:4000/posts/0106-dlang-ui-snippets-ii.html" />
<meta property="og:url" content="http://localhost:4000/posts/0106-dlang-ui-snippets-ii.html" />
<meta property="og:site_name" content="gtkDcoding" />
<meta property="og:type" content="article" />
<meta property="article:published_time" content="2020-04-03T00:00:00-04:00" />
<meta name="twitter:card" content="summary" />
<meta property="twitter:title" content="0106: D Snippets II - A Generic Observer" />
<script type="application/ld+json">
{"@context":"https://schema.org","@type":"BlogPosting","author":{"@type":"Person","name":"Ron Tarrant"},"dateModified":"2020-04-03T00:00:00-04:00","datePublished":"2020-04-03T00:00:00-04:00","description":"This GTK Tutorial covers a generic Observer pattern implemented in D.","headline":"0106: D Snippets II - A Generic Observer","mainEntityOfPage":{"@type":"WebPage","@id":"http://localhost:4000/posts/0106-dlang-ui-snippets-ii.html"},"url":"http://localhost:4000/posts/0106-dlang-ui-snippets-ii.html"}</script>
<!-- End Jekyll SEO tag -->
<link rel="stylesheet" href="../assets/main.css">
  <link rel="stylesheet" href="../css/style.css" /><link type="application/atom+xml" rel="alternate" href="http://localhost:4000/feed.xml" title="gtkDcoding" /></head>
<body><header class="site-header" role="banner">

  <div class="wrapper"><a class="site-title" rel="author" href="../">gtkDcoding</a><nav class="site-nav">
        <input type="checkbox" id="nav-trigger" class="nav-trigger" />
        <label for="nav-trigger">
          <span class="menu-icon">
            <svg viewBox="0 0 18 15" width="18px" height="15px">
              <path d="M18,1.484c0,0.82-0.665,1.484-1.484,1.484H1.484C0.665,2.969,0,2.304,0,1.484l0,0C0,0.665,0.665,0,1.484,0 h15.032C17.335,0,18,0.665,18,1.484L18,1.484z M18,7.516C18,8.335,17.335,9,16.516,9H1.484C0.665,9,0,8.335,0,7.516l0,0 c0-0.82,0.665-1.484,1.484-1.484h15.032C17.335,6.031,18,6.696,18,7.516L18,7.516z M18,13.516C18,14.335,17.335,15,16.516,15H1.484 C0.665,15,0,14.335,0,13.516l0,0c0-0.82,0.665-1.483,1.484-1.483h15.032C17.335,12.031,18,12.695,18,13.516L18,13.516z"/>
            </svg>
          </span>
        </label>

        <div class="trigger"><a class="page-link" href="../about.html">About</a><a class="page-link" href="../index-reverse.html">Posts in Date Order</a><a class="page-link" href="../topics.html">Blog Posts by Topic</a></div>
      </nav></div>
</header>
<main class="page-content" aria-label="Content">
      <div class="wrapper">
        <article class="post h-entry" itemscope itemtype="http://schema.org/BlogPosting">
	<header class="post-header">
		<link rel="stylesheet" href="../css/font_size.css" />
		<link rel="stylesheet" href="../css/figure.css" />
		<link rel="stylesheet" href="../css/topics/dlang.css" />  <!-- sub in the tag/topic -->
		<link rel="stylesheet" href="../css/modal.css" />
		<link rel="stylesheet" href="../css/post.css" />
		<link rel="stylesheet" href="../css/mascot_effects.css" />

		
		
		<p class="post-meta">
		<time class="dt-published" datetime="2020-04-03T00:00:00-04:00" itemprop="datePublished">Friday, April 3, 2020
		</time>• by <span itemprop="author" itemscope itemtype="http://schema.org/Person"><span class="p-author h-card" itemprop="name">Ron Tarrant</span></span></p>
	</header>

	<div class="post-content e-content" itemprop="articleBody">
		<div class="skew-line"></div>
		<h1 id="0106-d-language-snippets-ii---a-generic-observer">0106: D-language Snippets II - A Generic Observer</h1>

<p>Picking up from last time…</p>

<p>We discussed the difference between the <em>Observer</em> and <em>Singleton</em> patterns, then took a closer look at both the generic <em>Singleton</em> and a specific example of the <em>Singleton</em> at work. This time, we’ll do the same thing with the <em>Observer</em>.</p>

<h2 id="the-observer-pattern">The Observer Pattern</h2>

<p><em>Note: There is no UI for this example, just the output to the terminal.</em></p>

<!-- 0, 1 -->
<!-- first occurrence of application and terminal screen shots on a single page -->
<div class="screenshot-frame">
	<div class="frame-header">
		Results of this example:
	</div>
	<div class="frame-terminal">
		<figure class="right">
			<img id="img1" src="../images/screenshots/021_oop/oop_01_term.png" alt="Current example terminal output" />		<!-- img#, filename -->

			<!-- Modal for terminal shot -->
			<div id="modal1" class="modal">																				<!-- modal# -->
				<span class="close1">&times;</span>																		<!-- close# -->
				<img class="modal-content" id="img11" />																		<!-- img## -->
				<div id="caption"></div>
			</div>
			
			<script>
			// Get the modal
			var modal = document.getElementById("modal1");																	// modal#
			
			// Get the image and insert it inside the modal - use its "alt" text as a caption
			var img = document.getElementById("img1");																		// img#
			var modalImg = document.getElementById("img11");																// img##
			var captionText = document.getElementById("caption");

			img.onclick = function()
			{
			  modal.style.display = "block";
			  modalImg.src = this.src;
			  captionText.innerHTML = this.alt;
			}
			
			// Get the <span> element that closes the modal
			var span = document.getElementsByClassName("close1")[0];														// close#
			
			// When the user clicks on <span> (x), close the modal
			span.onclick = function()
			{ 
				modal.style.display = "none";
			}
			</script>

			<figcaption>
				Current example terminal output (click for enlarged view)
			</figcaption>
		</figure>
	</div>

	<div class="frame-footer">																								<!-- ------------- filename (below) --------- -->
		The code file for this example is available <a href="https://github.com/rontarrant/gtkd_demos/blob/master/021_oop/oop_01_observer.d" target="_blank">here</a>.
	</div>
</div>
<!-- end of snippet for first (1st) occurrence of application and terminal screen shots on a single page -->

<p>And because there’s no UI, we’ll start with…</p>

<h3 id="the-main-function">The main() Function</h3>

<p>All we do in <code class="language-plaintext highlighter-rouge">main()</code> is instantiate all the bits we need, then run the test a few times.</p>

<div class="language-d highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">void</span> <span class="n">main</span><span class="p">()</span>
<span class="p">{</span>
	<span class="c1">// initialize objects</span>
	<span class="n">Subject</span> <span class="n">subject</span> <span class="p">=</span> <span class="k">new</span> <span class="n">Subject</span><span class="p">();</span>
	<span class="n">Observer</span> <span class="n">observer1</span> <span class="p">=</span> <span class="k">new</span> <span class="n">Observer</span><span class="p">(</span><span class="s">"First Observer..."</span><span class="p">,</span> <span class="n">subject</span><span class="p">);</span>
	<span class="n">Observer</span> <span class="n">observer2</span> <span class="p">=</span> <span class="k">new</span> <span class="n">Observer</span><span class="p">(</span><span class="s">"Second Observer.."</span><span class="p">,</span> <span class="n">subject</span><span class="p">);</span>
	
	<span class="c1">// change state</span>
	<span class="k">foreach</span><span class="p">(</span><span class="kt">int</span> <span class="n">i</span><span class="p">;</span> <span class="mf">0..4</span><span class="p">)</span>
	<span class="p">{</span>
		<span class="n">writeln</span><span class="p">(</span><span class="s">"\nChanging state of Subject..."</span><span class="p">);</span>
		<span class="n">subject</span><span class="p">.</span><span class="n">change</span><span class="p">();</span>
		<span class="n">observer1</span><span class="p">.</span><span class="n">reportState</span><span class="p">();</span>
		<span class="n">observer2</span><span class="p">.</span><span class="n">reportState</span><span class="p">();</span>
	<span class="p">}</span>
	
<span class="p">}</span> <span class="c1">// main()</span>
</code></pre></div></div>

<p>In the preamble, we instantiate three objects—one to be watched, and two others to do the watching. (Make sure to instantiate the subject of observation first.)</p>

<p>Next comes the heart of our demo, a loop that:</p>

<ul>
  <li>toggles the state of the watched object between true and false a few times, and</li>
  <li>calls upon each of the <em>Observers</em> to tell us what they see.</li>
</ul>

<p>The loop spits out proof that the dynamic between <em>Observers</em> and watched object is working.</p>

<h3 id="the-observer-class">The Observer Class</h3>

<p>Now we get into the actual <em>Observer</em> code, starting with the class named for the pattern:</p>

<div class="language-d highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="n">Observer</span>
<span class="p">{</span>
	<span class="nb">string</span> <span class="n">idString</span><span class="p">;</span>
	<span class="kt">bool</span> <span class="n">subjectState</span><span class="p">;</span>
	
	<span class="k">this</span><span class="p">(</span><span class="nb">string</span> <span class="n">id</span><span class="p">,</span> <span class="n">Subject</span> <span class="n">subject</span><span class="p">)</span>
	<span class="p">{</span>
		<span class="n">idString</span> <span class="p">=</span> <span class="n">id</span><span class="p">;</span>
		<span class="n">subject</span><span class="p">.</span><span class="n">addObserver</span><span class="p">(</span><span class="k">this</span><span class="p">);</span>
		
	<span class="p">}</span> <span class="c1">// this()</span>
	
	
	<span class="kt">void</span> <span class="n">reactToSubjectStateChange</span><span class="p">(</span><span class="kt">bool</span> <span class="n">newState</span><span class="p">)</span>
	<span class="p">{</span>
		<span class="n">subjectState</span> <span class="p">=</span> <span class="n">newState</span><span class="p">;</span>
		
	<span class="p">}</span> <span class="c1">// reactToSubjectStateChange()</span>
	
	
	<span class="kt">void</span> <span class="n">reportState</span><span class="p">()</span>
	<span class="p">{</span>
		<span class="n">writeln</span><span class="p">(</span><span class="s">"Viewing from "</span><span class="p">,</span> <span class="n">idString</span><span class="p">,</span> <span class="s">". The subject's state is now: "</span><span class="p">,</span> <span class="n">subjectState</span><span class="p">);</span>

	<span class="p">}</span> <span class="c1">// reportState()</span>
	
<span class="p">}</span> <span class="c1">// class Observer</span>
</code></pre></div></div>

<p>In the preamble we find an <code class="language-plaintext highlighter-rouge">ID</code>. It’s not strictly necessary for production-level code… unless you need to track which observer is watching at any given time. For a demonstration such as this, it can also give us proof that the mechanism is working.</p>

<p>In the <code class="language-plaintext highlighter-rouge">reactToSubjectStateChange()</code> function the <code class="language-plaintext highlighter-rouge">Observer</code>’s <code class="language-plaintext highlighter-rouge">subjectState</code> <em>Boolean</em> is the only thing we update, but it stands in for whatever housekeeping the <em>Observer</em> would ordinarily do when the watched object reports changes.</p>

<p><em>Note: this function is never called by anything other than the watched object. This is because we only want an <code class="language-plaintext highlighter-rouge">Observer</code> to react to changes reported by the watched object… in other words, only when new information comes straight from the horse’s mouth.</em></p>

<p>Now let’s look at…</p>

<h3 id="the-subjectwatchedobserved-class">The Subject/Watched/Observed Class</h3>

<p>In a nutshell, any watched object will have:</p>

<ul>
  <li>one or more dynamic properties,</li>
  <li>a mechanism for adding (and, in real-world use cases, perhaps, removing) <em>Observers</em>, and</li>
  <li>a second mechanism for reporting to the <em>Observers</em> any time a change takes place in one of its dynamic properties.</li>
</ul>

<h4 id="preamble">Preamble</h4>

<div class="language-d highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">bool</span> <span class="n">switcherState</span><span class="p">;</span>
<span class="n">Observer</span><span class="p">[]</span> <span class="n">observers</span><span class="p">;</span>
</code></pre></div></div>

<p>So, as expected, we have a bit of data that the <em>Observers</em> want to track and an array that will hold a list of those <em>Observers</em>.</p>

<h4 id="the-constructor">The Constructor</h4>

<p>This constructor is pretty straightforward:</p>

<div class="language-d highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">this</span><span class="p">()</span>
<span class="p">{</span>
	<span class="n">switcherState</span> <span class="p">=</span> <span class="kc">false</span><span class="p">;</span>
	
<span class="p">}</span> <span class="c1">// this()</span>
</code></pre></div></div>

<p>As can be seen, it just sets the initial state of the data.</p>

<h4 id="the-addobserver-function">The addObserver Function</h4>

<div class="language-d highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">void</span> <span class="n">addObserver</span><span class="p">(</span><span class="n">Observer</span> <span class="n">observer</span><span class="p">)</span>
<span class="p">{</span>
	<span class="n">observers</span> <span class="p">~=</span> <span class="n">observer</span><span class="p">;</span>
	<span class="n">observer</span><span class="p">.</span><span class="n">reactToSubjectStateChange</span><span class="p">(</span><span class="n">switcherState</span><span class="p">);</span>
	
<span class="p">}</span> <span class="c1">// addObserver()</span>
</code></pre></div></div>

<p>Here we add a new <em>Observer</em> to the watched object’s list and get it up to speed right away as to the state of the <code class="language-plaintext highlighter-rouge">switcherState</code> property. If we had a bunch of properties that <code class="language-plaintext highlighter-rouge">Observer</code>s needed to be aware of, we can pass as many as necessary to the <code class="language-plaintext highlighter-rouge">reactToSubjectStateChange()</code> function.</p>

<h4 id="the-updateall-function">The updateAll Function</h4>

<div class="language-d highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">void</span> <span class="n">updateAll</span><span class="p">()</span>
<span class="p">{</span>
	<span class="k">foreach</span><span class="p">(</span><span class="n">observer</span><span class="p">;</span> <span class="n">observers</span><span class="p">)</span>
	<span class="p">{</span>
		<span class="n">observer</span><span class="p">.</span><span class="n">reactToSubjectStateChange</span><span class="p">(</span><span class="n">switcherState</span><span class="p">);</span>
			
	<span class="p">}</span>
		
<span class="p">}</span> <span class="c1">// updateAll()</span>
</code></pre></div></div>

<p>This steps through the list of <em>Observers</em> and informs them of the change. <em>Observers</em> can have different implementations of <code class="language-plaintext highlighter-rouge">reactToSubjectStateChange()</code> which allows each to react in its own unique way to changes in the watched object.</p>

<h4 id="the-change-function">The change Function</h4>

<p>And finally, we have:</p>

<div class="language-d highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">void</span> <span class="n">change</span><span class="p">()</span>
<span class="p">{</span>
	<span class="k">if</span><span class="p">(</span><span class="n">switcherState</span> <span class="p">==</span> <span class="kc">true</span><span class="p">)</span>
	<span class="p">{</span>
		<span class="n">switcherState</span> <span class="p">=</span> <span class="kc">false</span><span class="p">;</span>
	<span class="p">}</span>
	<span class="k">else</span>
	<span class="p">{</span>
		<span class="n">switcherState</span> <span class="p">=</span> <span class="kc">true</span><span class="p">;</span>
	<span class="p">}</span>
	
	<span class="n">updateAll</span><span class="p">();</span>
	
<span class="p">}</span> <span class="c1">// change()</span>
</code></pre></div></div>

<p>This is our change-for-change’s-sake function and is here for demonstration purposes only. It forces a change that the entire system then reacts to.</p>

<h2 id="conclusion">Conclusion</h2>

<p>This article is running long, so we’ll have to wait until next time to look over the <em>Observer</em> at work example.</p>

<p>Take care, and see you then.</p>

<div class="blog-nav">
	<div style="float: left;">
		<a href="./0105-dlang-ui-snippets-i.html">Previous: D Snippets I - Singleton vs. Observer</a>
	</div>
	<div style="float: right;">
		<a href="./0107-dlang-ui-snippets-iii.html">Next: D Snippets III - Practical Observer</a>
	</div>
</div>
<p>
	<h3></h3>
<div class="inpage-frame">
	<a href="https://github.com/sponsors/rontarrant">
		<BR>
		<BR>
		<B>Is this article useful? Educational? Entertaining, perhaps?</B>
		<BR>
		<figure class="left">
			<img src="../images/favorite_32.png" alt="Sponsorship heart" style="width: 32px; height: 32px;">
		</figure>
		You're free to accept or decline this invitation to become our newest sponsor.
	</a>
</div>
	<h4 class="comment-blurb"><B>Comments? Questions? Observations?</B></h4>
	<p>
		Did we miss a tidbit of information that would make this post even more informative? Let's talk about it in the comments.
	</p>
	<script src="https://utteranc.es/client.js"
		repo="rontarrant"
		issue-term="pathname"
		theme="github-light"
		crossorigin="anonymous"
		async>
	</script>
	<ul>
		<li> come on over to the <a href="https://forum.dlang.org/">D Language Forum</a> and look for one of the <i>gtkDcoding</i> announcement posts, </li>
		<li> drop by <a href="https://forum.gtkd.org/">the <i>GtkD Forum</i></a>,</li>
		<li> follow the link below to email me, or</li>
		<li> go to the	<a href="https://www.facebook.com">gtkDcoding Facebook page.</a></li>
	</ul>
</p>
<p> You can also subscribe <a href="/feed.xml">via RSS</a> so you won't miss anything. Thank you very much for dropping by.</p>
<p>&copy; Copyright 2025 Ron Tarrant </p>
</div>

	<a class="u-url" href="./0106-dlang-ui-snippets-ii.html" hidden></a>
</article>

      </div>
    </main><footer class="site-footer h-card">
  <data class="u-url" href="/"></data>

  <div class="wrapper">

    <h2 class="footer-heading">gtkDcoding</h2>

    <div class="footer-col-wrapper">
      <div class="footer-col footer-col-1">
        <ul class="contact-list">
          <li class="p-name">Ron Tarrant</li><li><a class="u-email" href="mailto:gtkDcoding@gmail.com">gtkDcoding@gmail.com</a></li></ul>
      </div>

      <div class="footer-col footer-col-2"><ul class="social-media-list"><li><a href="https://github.com/rontarrant"><svg class="svg-icon"><use xlink:href="../assets/minima-social-icons.svg#github"></use></svg> <span class="username">rontarrant</span></a></li></ul>
</div>

      <div class="footer-col footer-col-3">
        <p>Simple examples of how to use GtkD to build GUI applications.</p>
      </div>
    </div>

  </div>

</footer>
</body>

</html>
